package day240925;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        try {
            // 获取请求中的所有Cookie
            Cookie[] cookies = request.getCookies();
            boolean showButton = true;

            // 检查是否有我们设置的Cookie
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("visited".equals(cookie.getName())) {
                        // 如果找到visited的Cookie，检查是否过期
                        showButton = false;
                        break;
                    }
                }
            }

            // 如果需要显示按钮，则创建按钮并设置Cookie
            if (showButton) {
                out.println("<html>");
                out.println("<head><title> Welcome Page </title></head>");
                out.println("<body>");
                out.println("<p>Welcome! Click the button to close the message.</p>");
                out.println("<form action=\"./closeMessage\" method=\"post\">");
                out.println("<input type=\"submit\" value=\"Close\" />");
                out.println("</form>");
                out.println("</body>");
                out.println("</html>");
            } else {
                out.println("<html>");
                out.println("<head><title> Welcome Page </title></head>");
                out.println("<body>");
                out.println("<p>Welcome back! The message is closed.</p>");
                out.println("</body>");
                out.println("</html>");
            }
        } finally {
            out.close();
        }
    }
}

